export function useLocation() {
  //获取授权
  const getLocation = () => {
    console.log('11')

    return new Promise<UniNamespace.GetLocationSuccess>((resolve, reject) => {
      // 提前检测授权
      uni.getSetting({
        success(res) {
          console.log(res)
          const authSetting = res.authSetting['scope.userLocation']
          if (authSetting) {
            resolve(getCurrentLocation())
          } else if (authSetting === false) {
            tipToast()
            reject('未授权')
          } else {
            uni.authorize({
              scope: 'scope.userLocation',
              success: (res) => {
                resolve(getCurrentLocation())
              },
              fail: (err) => {
                console.log(err)
                tipToast()
                reject('未授权')
              },
            })
          }
        },
      })
    })
  }

  // 获取定位经纬度
  const getCurrentLocation = () => {
    return new Promise<UniNamespace.GetLocationSuccess>((resolve, reject) => {
      uni.getLocation({
        type: 'wgs84',
        success(res) {
          resolve(res)
        },
        fail(err) {
          if (err.errMsg == 'getLocation:fail auth deny') {
            tipToast()
            reject('拒绝授权')
          } else if (
            err.errMsg === 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF' ||
            err.errMsg === 'getLocation:fail system permission denied' ||
            err.errMsg === 'getLocation:fail:system permission denied'
          ) {
            uni.showModal({
              title: '您未开启手机定位',
              content: '请在系统设置中打开定位服务，以便我们为您提供更好的服务',
              showCancel: false,
            })
            reject('手机定位未开启')
          }
        },
      })
    })
  }

  const tipToast = () => {
    uni.showModal({
      title: '您未开启地理位置授权',
      content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
      success: (res) => {
        if (res.confirm) {
          uni.openSetting()
        }
      },
    })
  }

  return {
    getLocation,
    getCurrentLocation,
  }
}
